const oracledb = require('oracledb');
const _ = require('lodash');
const Mock = require("mockjs");



// const mockjson={
//     "overtime|10": [{
//         "SAP_NO|80000000-89999999": 0,
//         "USER_NAME": "@cname",
//         "HOLIDAY_OVERTIME|1-30": 0,
//         "OVERTIME|1-100": 0,
//         "DELAY_TIME|1-100": 0,
//         "PRE_BREAKOFF|10-100": 0,
//         "PRE_DEDUCTION|10-100": 0,
//         "BREAKOFF|10-100": 0,
//         "DEDUCTION|10-100": 0,
//         "CREATE_BY": "admin"
//     }]
// };

// const tablename = 'ts_overtime';

const mockjson = {
    "list|10": [{
        "BEFORE_LAST_YEAR|90-99": 0,
        "LAST_YEAR|90-99": 0,
        "CURR_YEAR_TARGET|90-99": 0,
        "CURR_YEAR|90-99": 0,
        "LAST_MONTH|90-99": 0,
        "BEFORE_LAST_WEEk|90-99": 0,
        "LAST_WEEk|90-99": 0,
        "CURR_WEEk|90-99": 0,
        "CREATE_BY": "admin"
    }]
};

const tablename = 'ts_efficiency';


const data = Mock.mock(mockjson);
console.log(JSON.stringify(data))

oracledb.outFormat = oracledb.OUT_FORMAT_OBJECT;

function insert(connection, data) {
    let keys = [], values = [];
    console.log(JSON.stringify(data))
    for (let key in data) {
        keys.push(key);
        values.push(data[key]);
    }
    let lastsql = `INSERT INTO ${tablename} (${keys.join(',')}) VALUES (${"'" + values.join("','") + "'"}) RETURN ID INTO :id`;

    console.log(lastsql)
    return connection.execute(
        lastsql,
        { id: { type: oracledb.DB_TYPE_VARCHAR, dir: oracledb.BIND_OUT } }
    );
}

async function run() {

    let connection;

    try {
        connection = await oracledb.getConnection({
            user: "jmcapp",
            password: 'jmcapp',
            connectString: "localhost:1521/orcl"
        });
        for (let key in data)
            for (let user of data[key]) {
                const result = await insert(connection, user);
                console.log('result->' + JSON.stringify(result.outBinds.id));
            }

        connection.commit();

    } catch (err) {
        console.error(err);
    } finally {
        if (connection) {
            try {
                await connection.close();
            } catch (err) {
                console.error(err);
            }
        }
    }
}

run();